<template>
  <div class="interview-result-container">
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">面试结果</h1>
          <div class="page-subtitle">{{ interview?.title || '面试结果登记' }}</div>
        </div>
        <div class="header-actions">
          <el-button @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </div>

    <div class="page-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="8" animated />
      </div>

      <div v-else-if="interview" class="result-content">
        <!-- 面试基本信息 -->
        <div class="interview-info-section">
          <el-card class="info-card" shadow="never">
            <template #header>
              <div class="card-header">
                <h3>面试信息</h3>
                <el-tag :type="getStatusTagType(interview.status)" size="large">
                  {{ interview.status_display }}
                </el-tag>
              </div>
            </template>

            <el-descriptions :column="2" border>
              <el-descriptions-item label="面试标题">{{ interview.title }}</el-descriptions-item>
              <el-descriptions-item label="面试类型">{{ interview.type_display }}</el-descriptions-item>
              <el-descriptions-item label="学生姓名">{{ interview.student_name }}</el-descriptions-item>
              <el-descriptions-item label="面试官">{{ interview.interviewer_name }}</el-descriptions-item>
              <el-descriptions-item label="安排时间">
                {{ formatDateTime(interview.scheduled_time) }}
              </el-descriptions-item>
              <el-descriptions-item label="实际时间">
                {{ formatActualTime(interview) }}
              </el-descriptions-item>
              <el-descriptions-item label="面试地点">{{ interview.location || '-' }}</el-descriptions-item>
              <el-descriptions-item label="面试时长">{{ interview.duration || '-' }}分钟</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>

        <!-- 结果提交区域 -->
        <div class="result-submission-section">
          <el-row :gutter="24">
            <!-- 老师评价 -->
            <el-col :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
              <el-card class="submission-card teacher-card" shadow="never">
                <template #header>
                  <div class="card-header">
                    <h3>
                      <el-icon><User /></el-icon>
                      老师评价
                    </h3>
                    <el-tag v-if="result?.teacher_submitted_at" type="success" size="small">
                      已提交
                    </el-tag>
                    <el-tag v-else type="warning" size="small">
                      待提交
                    </el-tag>
                  </div>
                </template>

                <div v-if="result?.teacher_submitted_at && !isTeacher" class="submitted-content">
                  <div class="feedback-item">
                    <h4>面试反馈</h4>
                    <p>{{ result.teacher_feedback || '暂无反馈' }}</p>
                  </div>
                  <div class="feedback-item">
                    <h4>评分</h4>
                    <div class="score-display">
                      <el-rate
                        v-model="displayTeacherScore"
                        disabled
                        show-score
                        text-color="#ff9900"
                        score-template="{value}分"
                      />
                    </div>
                  </div>
                  <div class="feedback-item">
                    <h4>改进建议</h4>
                    <p>{{ result.teacher_suggestions || '暂无建议' }}</p>
                  </div>
                  <div class="submit-time">
                    提交时间：{{ formatDateTime(result.teacher_submitted_at) }}
                  </div>
                </div>

                <div v-else-if="isTeacher" class="submission-form">
                  <el-form
                    ref="teacherFormRef"
                    :model="teacherForm"
                    :rules="teacherRules"
                    label-width="100px"
                  >
                    <el-form-item label="面试反馈" prop="teacher_feedback">
                      <el-input
                        v-model="teacherForm.teacher_feedback"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入对学生面试表现的详细反馈"
                        :disabled="result?.teacher_submitted_at"
                      />
                    </el-form-item>

                    <el-form-item label="面试评分" prop="teacher_score">
                      <el-rate
                        v-model="teacherForm.teacher_score"
                        show-score
                        text-color="#ff9900"
                        score-template="{value}分"
                        :disabled="result?.teacher_submitted_at"
                      />
                    </el-form-item>

                    <el-form-item label="改进建议" prop="teacher_suggestions">
                      <el-input
                        v-model="teacherForm.teacher_suggestions"
                        type="textarea"
                        :rows="3"
                        placeholder="请提供具体的改进建议和发展方向"
                        :disabled="result?.teacher_submitted_at"
                      />
                    </el-form-item>

                    <el-form-item v-if="!result?.teacher_submitted_at">
                      <el-button
                        type="primary"
                        @click="submitTeacherResult"
                        :loading="submittingTeacher"
                      >
                        提交评价
                      </el-button>
                    </el-form-item>

                    <div v-else class="submit-time">
                      已于 {{ formatDateTime(result.teacher_submitted_at) }} 提交
                    </div>
                  </el-form>
                </div>

                <div v-else class="waiting-message">
                  <el-empty description="等待老师提交评价" />
                </div>
              </el-card>
            </el-col>

            <!-- 学生反馈 -->
            <el-col :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
              <el-card class="submission-card student-card" shadow="never">
                <template #header>
                  <div class="card-header">
                    <h3>
                      <el-icon><UserFilled /></el-icon>
                      学生反馈
                    </h3>
                    <el-tag v-if="result?.student_submitted_at" type="success" size="small">
                      已提交
                    </el-tag>
                    <el-tag v-else type="warning" size="small">
                      待提交
                    </el-tag>
                  </div>
                </template>

                <div v-if="result?.student_submitted_at && !isStudent" class="submitted-content">
                  <div class="feedback-item">
                    <h4>面试反馈</h4>
                    <p>{{ result.student_feedback || '暂无反馈' }}</p>
                  </div>
                  <div class="feedback-item">
                    <h4>自评分数</h4>
                    <div class="score-display">
                      <el-rate
                        v-model="displayStudentScore"
                        disabled
                        show-score
                        text-color="#ff9900"
                        score-template="{value}分"
                      />
                    </div>
                  </div>
                  <div class="feedback-item">
                    <h4>面试体验</h4>
                    <p>{{ result.student_experience || '暂无体验分享' }}</p>
                  </div>
                  <div class="submit-time">
                    提交时间：{{ formatDateTime(result.student_submitted_at) }}
                  </div>
                </div>

                <div v-else-if="isStudent" class="submission-form">
                  <el-form
                    ref="studentFormRef"
                    :model="studentForm"
                    :rules="studentRules"
                    label-width="100px"
                  >
                    <el-form-item label="面试反馈" prop="student_feedback">
                      <el-input
                        v-model="studentForm.student_feedback"
                        type="textarea"
                        :rows="4"
                        placeholder="请分享您对本次面试的感受和收获"
                        :disabled="result?.student_submitted_at"
                      />
                    </el-form-item>

                    <el-form-item label="自评分数" prop="student_self_score">
                      <el-rate
                        v-model="studentForm.student_self_score"
                        show-score
                        text-color="#ff9900"
                        score-template="{value}分"
                        :disabled="result?.student_submitted_at"
                      />
                    </el-form-item>

                    <el-form-item label="面试体验" prop="student_experience">
                      <el-input
                        v-model="studentForm.student_experience"
                        type="textarea"
                        :rows="3"
                        placeholder="请描述面试过程中的体验和感受"
                        :disabled="result?.student_submitted_at"
                      />
                    </el-form-item>

                    <el-form-item v-if="!result?.student_submitted_at">
                      <el-button
                        type="primary"
                        @click="submitStudentResult"
                        :loading="submittingStudent"
                      >
                        提交反馈
                      </el-button>
                    </el-form-item>

                    <div v-else class="submit-time">
                      已于 {{ formatDateTime(result.student_submitted_at) }} 提交
                    </div>
                  </el-form>
                </div>

                <div v-else class="waiting-message">
                  <el-empty description="等待学生提交反馈" />
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 完成状态 -->
        <div v-if="result?.is_completed" class="completion-section">
          <el-card class="completion-card" shadow="never">
            <div class="completion-content">
              <div class="completion-icon">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="completion-text">
                <h3>面试已完成</h3>
                <p>双方已完成反馈提交，面试流程结束</p>
                <div class="completion-time">
                  完成时间：{{ formatDateTime(result.completed_at) }}
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <div v-else class="error-state">
        <el-empty description="面试信息不存在">
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft, User, UserFilled, CircleCheck
} from '@element-plus/icons-vue'
import interviewApi from '@/api/interview'
import { formatDateTime } from '@/utils/format'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submittingTeacher = ref(false)
const submittingStudent = ref(false)

const interview = ref(null)
const result = ref(null)

// 用户角色判断
const isTeacher = computed(() => ['teacher', 'admin'].includes(userStore.userInfo?.role))
const isStudent = computed(() => userStore.userInfo?.role === 'student')

// 显示用的评分（转换为5分制）
const displayTeacherScore = computed(() => {
  return result.value?.teacher_score ? Math.round(result.value.teacher_score) : 0
})

const displayStudentScore = computed(() => {
  return result.value?.student_self_score ? Math.round(result.value.student_self_score) : 0
})

// 老师表单
const teacherForm = reactive({
  teacher_feedback: '',
  teacher_score: 0,
  teacher_suggestions: ''
})

const teacherFormRef = ref()

const teacherRules = {
  teacher_feedback: [
    { required: true, message: '请输入面试反馈', trigger: 'blur' },
    { min: 10, message: '反馈内容不少于10个字符', trigger: 'blur' }
  ],
  teacher_score: [
    { required: true, message: '请给出面试评分', trigger: 'change' },
    { type: 'number', min: 1, max: 5, message: '评分范围为1-5分', trigger: 'change' }
  ],
  teacher_suggestions: [
    { required: true, message: '请提供改进建议', trigger: 'blur' }
  ]
}

// 学生表单
const studentForm = reactive({
  student_feedback: '',
  student_self_score: 0,
  student_experience: ''
})

const studentFormRef = ref()

const studentRules = {
  student_feedback: [
    { required: true, message: '请输入面试反馈', trigger: 'blur' },
    { min: 10, message: '反馈内容不少于10个字符', trigger: 'blur' }
  ],
  student_self_score: [
    { required: true, message: '请进行自我评分', trigger: 'change' },
    { type: 'number', min: 1, max: 5, message: '评分范围为1-5分', trigger: 'change' }
  ],
  student_experience: [
    { required: true, message: '请分享面试体验', trigger: 'blur' }
  ]
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    scheduled: 'primary',
    in_progress: 'warning',
    completed: 'success',
    cancelled: 'danger',
    expired: 'info'
  }
  return typeMap[status] || 'info'
}

// 格式化实际时间
const formatActualTime = (interview) => {
  if (!interview.actual_start_time) return '-'
  const start = formatDateTime(interview.actual_start_time)
  const end = interview.actual_end_time ? formatDateTime(interview.actual_end_time) : '进行中'
  return `${start} - ${end}`
}

// 获取面试详情
const fetchInterviewDetail = async () => {
  try {
    loading.value = true
    const interviewId = route.params.id
    
    const [interviewResponse, resultResponse] = await Promise.all([
      interviewApi.interview.getInterviewDetail(interviewId),
      interviewApi.interview.getInterviewResult(interviewId)
    ])
    
    interview.value = interviewResponse.data
    result.value = resultResponse.data
    
    // 填充表单数据
    if (result.value) {
      if (result.value.teacher_feedback) {
        Object.assign(teacherForm, {
          teacher_feedback: result.value.teacher_feedback,
          teacher_score: result.value.teacher_score || 0,
          teacher_suggestions: result.value.teacher_suggestions
        })
      }
      
      if (result.value.student_feedback) {
        Object.assign(studentForm, {
          student_feedback: result.value.student_feedback,
          student_self_score: result.value.student_self_score || 0,
          student_experience: result.value.student_experience
        })
      }
    }
  } catch (error) {
    console.error('获取面试详情失败:', error)
    ElMessage.error('获取面试详情失败')
  } finally {
    loading.value = false
  }
}

// 提交老师评价
const submitTeacherResult = async () => {
  try {
    await teacherFormRef.value.validate()
    submittingTeacher.value = true
    
    await interviewApi.result.teacherSubmitResult(result.value.id, teacherForm)
    ElMessage.success('评价提交成功')
    
    // 重新获取数据
    await fetchInterviewDetail()
  } catch (error) {
    console.error('提交评价失败:', error)
    ElMessage.error('提交评价失败')
  } finally {
    submittingTeacher.value = false
  }
}

// 提交学生反馈
const submitStudentResult = async () => {
  try {
    await studentFormRef.value.validate()
    submittingStudent.value = true
    
    await interviewApi.result.studentSubmitResult(result.value.id, studentForm)
    ElMessage.success('反馈提交成功')
    
    // 重新获取数据
    await fetchInterviewDetail()
  } catch (error) {
    console.error('提交反馈失败:', error)
    ElMessage.error('提交反馈失败')
  } finally {
    submittingStudent.value = false
  }
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 初始化
onMounted(() => {
  fetchInterviewDetail()
})
</script>

<style scoped>
.interview-result-container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  padding: 24px 32px;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 4px 0;
  line-height: 1.2;
}

.page-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.page-content {
  flex: 1;
  padding: 24px 32px;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

.loading-container {
  padding: 40px;
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.interview-info-section {
  margin-bottom: 8px;
}

.info-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.result-submission-section {
  margin-bottom: 8px;
}

.submission-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
  height: 100%;
}

.teacher-card {
  border-left: 4px solid #3b82f6;
}

.student-card {
  border-left: 4px solid #10b981;
}

.submitted-content {
  padding: 4px 0;
}

.feedback-item {
  margin-bottom: 20px;
}

.feedback-item h4 {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 8px 0;
}

.feedback-item p {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.6;
  margin: 0;
  background: #f9fafb;
  padding: 12px;
  border-radius: 6px;
  border-left: 3px solid #e5e7eb;
}

.score-display {
  display: flex;
  align-items: center;
  gap: 12px;
}

.submission-form {
  padding: 4px 0;
}

.waiting-message {
  padding: 40px 20px;
  text-align: center;
}

.submit-time {
  font-size: 12px;
  color: #9ca3af;
  text-align: right;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f3f4f6;
}

.completion-section {
  margin-top: 8px;
}

.completion-card {
  border: 1px solid #10b981;
  border-radius: 12px;
  overflow: hidden;
  background: linear-gradient(135deg, #ecfdf5, #f0fdf4);
}

.completion-content {
  display: flex;
  align-items: center;
  padding: 24px;
}

.completion-icon {
  width: 60px;
  height: 60px;
  background: #10b981;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  color: white;
  font-size: 28px;
}

.completion-text h3 {
  font-size: 20px;
  font-weight: 600;
  color: #065f46;
  margin: 0 0 4px 0;
}

.completion-text p {
  font-size: 14px;
  color: #047857;
  margin: 0 0 8px 0;
}

.completion-time {
  font-size: 12px;
  color: #059669;
}

.error-state {
  padding: 60px 20px;
  text-align: center;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #374151;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  transition: all 0.2s ease;
}

:deep(.el-textarea__inner:focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

:deep(.el-rate) {
  display: flex;
  align-items: center;
}

:deep(.el-rate__text) {
  margin-left: 8px;
  font-weight: 600;
  color: #374151;
}

/* 描述列表样式 */
:deep(.el-descriptions) {
  margin: 0;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #374151;
}

:deep(.el-descriptions__content) {
  color: #6b7280;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-content {
    padding: 20px 24px;
  }

  .header-content {
    padding: 0 24px;
  }
}

@media (max-width: 768px) {
  .page-content {
    padding: 16px 20px;
  }

  .header-content {
    padding: 0 20px;
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .result-content {
    gap: 16px;
  }

  .completion-content {
    flex-direction: column;
    text-align: center;
    padding: 20px;
  }

  .completion-icon {
    margin-right: 0;
    margin-bottom: 16px;
  }

  :deep(.el-descriptions) {
    font-size: 13px;
  }

  :deep(.el-descriptions__label) {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .page-header {
    padding: 20px 16px;
  }

  .page-content {
    padding: 16px;
  }

  .page-title {
    font-size: 24px;
  }

  .header-actions {
    flex-direction: column;
    gap: 8px;
  }

  .header-actions .el-button {
    width: 100%;
  }

  .card-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .completion-content {
    padding: 16px;
  }

  .completion-icon {
    width: 50px;
    height: 50px;
    font-size: 24px;
  }
}
</style>
